package com.kushe.site.controller;


import com.kushe.dao.*;
import com.kushe.entity.User;
import com.kushe.site.form.EditInfoForm;
import com.kushe.site.form.LoginForm;
import com.kushe.site.form.RegisterForm;
import com.kushe.util.KSController;
import com.kushe.util.SessionEnv;
import com.kushe.util.SessionEnvFactory;
import com.kushe.util.core.DaoFactory;
import com.kushe.util.tools.CookiesUtil;
import org.nutz.dao.QueryResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WhiteBlue on 15/3/31.
 */
@org.springframework.stereotype.Controller
@RequestMapping(value = "/user")
public class UserController extends KSController {

    /**
     * 登陆
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Object login(HttpServletRequest request, HttpServletResponse response) {
        this.clearAttr(request);
        LoginForm form = new LoginForm();
        if (form.validate(request)) {
            User user = DaoFactory.getDao(UserDao.class).getByPw((String) form.getEmail().getValue(), (String) form.getPassword().getValue());
            if (user == null) {
                request.getSession().setAttribute("msg", "用户名或密码错误");
                return this.redirect("/login");
            } else {
                request.getSession().setAttribute("sessionEnv", SessionEnvFactory.makeSessionEnv(user));
                request.getSession().setMaxInactiveInterval(3600 * 3);
                setCookies(user, response);
                request.getSession().setAttribute("msg", "登陆成功");
                return this.redirect("/");
            }
        } else {
            request.getSession().setAttribute("msg", "验证失败");
            return this.redirect("/");
        }
    }


    /**
     * 添加收藏
     */
    @RequestMapping(value = "addCollect", method = RequestMethod.GET)
    public Object addCollect(HttpServletRequest request, @RequestParam(value = "design", required = true) int design_id) {
        User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);
        designDao.addCollect(design_id, user.getId());
        return this.redirect("/design?design=" + design_id);
    }


    /**
     * 删除收藏
     */
    @RequestMapping(value = "deleteCollect", method = RequestMethod.GET)
    public Object deleteCollect(HttpServletRequest request, @RequestParam(value = "design", required = true) int design_id) {
        User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);
        designDao.deleteCollect(design_id, user.getId());
        return this.redirect("/design?design=" + design_id);
    }


    /**
     * 注册
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public Object register(HttpServletRequest request, HttpServletResponse response) {
        RegisterForm form = new RegisterForm();
        if (!form.validate(request)) {
            request.getSession().setAttribute("msg", "验证失败");
            return this.redirect("/");
        } else {
            UserDao userDao = DaoFactory.getDao(UserDao.class);
            if (!userDao.checkEmail(form.getEmail())) {
                request.getSession().setAttribute("msg", "邮箱已被占用");
                return this.redirect("/register");
            }
            User user = userDao.addUser(form.getEmail(), form.getName(), form.getPassword());
            if (user != null) {
                request.getSession().setAttribute("sessionEnv", SessionEnvFactory.makeSessionEnv(user));
                request.getSession().setMaxInactiveInterval(3600);
                setCookies(user, response);
                request.getSession().setAttribute("msg", "注册成功");
                return this.redirect("/");
            } else {
                request.getSession().setAttribute("msg", "注册失败");
                return this.redirect("/");
            }
        }
    }

    /**
     * 注销
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public Object logout(HttpServletRequest request, HttpServletResponse response) {
        this.clearAttr(request);
        if (request.getSession().getAttribute("user") != null) {
            request.getSession().removeAttribute("sessionEnv");
            CookiesUtil.removeCookie(response, "user");
        }
        request.getSession().setAttribute("msg", "注销成功");
        return this.redirect("/");
    }


    /**
     * 我的订单
     */
    @RequestMapping(value = "myOrder", method = RequestMethod.GET)
    public Object myOrder(@RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request) {
        this.clearAttr(request);
        User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
        this.setAttr("page", DaoFactory.getDao(OrderDao.class).myOrder(user.getId(), page));
        this.setAttr("actionUrl", "/user/myOrder?page=");
        return this.render("/user/myOrder.html");
    }


    /**
     * 我的收藏
     */
    @RequestMapping(value = "myCollect", method = RequestMethod.GET)
    public Object myCollect(@RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request) {
        this.clearAttr(request);
        User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
        this.setAttr("page", DaoFactory.getDao(DesignDao.class).getByCollect(page, user.getId()));
        this.setAttr("actionUrl", "/user/myCollect?page=");
        return this.render("/user/myCollect.html");
    }


    /**
     * 我的消息
     */
    @RequestMapping(value = "myNotice", method = RequestMethod.GET)
    public Object myNotice(@RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request) {
        this.clearAttr(request);
        User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
        QueryResult queryResult = DaoFactory.getDao(NoticeDao.class).listMyMessage(user.getId(), page);
        this.setAttr("page", queryResult);
        this.setAttr("actionUrl", "/user/myNotice?page=");
        return this.render("/user/myNotice.html");
    }


    /**
     * 用户的信息
     */
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    public Object userInfo(@RequestParam(value = "user", required = true) int user_id, HttpServletRequest request) {
        this.clearAttr(request);
        User user = DaoFactory.getDao(UserDao.class).get(user_id);
        if (user != null) {
            DesignDao designDao = DaoFactory.getDao(DesignDao.class);
            this.setAttr("user", user);
            this.setAttr("designs", designDao.getForUserLimit(user.getId()));
            User me = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
            if (me != null) {
                if (me.getId() == user_id) {
                    ImagesDao imagesDao = DaoFactory.getDao(ImagesDao.class);
                    OrderDao orderDao = DaoFactory.getDao(OrderDao.class);
                    this.setAttr("collects", designDao.getForCollectLimit(user.getId()));
                    this.setAttr("orders", orderDao.myOrderLimit(user.getId()));
                    this.setAttr("images", imagesDao.getForUserLimit(user.getId()));
                }
            } else
                this.setAttr("is_me", false);
            return render("/user/info.html");
        } else {
            return renderError("请求有误");
        }
    }


    /**
     * 我的信息(编辑)
     */
    @RequestMapping(value = "myInfo", method = RequestMethod.GET)
    public Object myInfo(HttpServletRequest request) {
        this.clearAttr(request);
        return render("/user/infoEdit.html");
    }


    /**
     * 编辑信息接口
     */
    @RequestMapping(value = "editInfo", method = RequestMethod.POST)
    public Object editInfo(HttpServletRequest request) {
        this.clearAttr(request);
        EditInfoForm form = new EditInfoForm(request);
        if (!form.verify()) {
            this.setAttr("msg", "验证失败");
            return redirect("/user/myInfo");
        } else {
            User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
            user = DaoFactory.getDao(UserDao.class).editInfo(user, form.getString("feeling"), form.getString("name"), form.getInt("sex"));
            request.getSession().setAttribute("user", user);
            return redirect("/user/myInfo");
        }
    }


    /**
     * 编辑信息接口
     */
    @RequestMapping(value = "editAddress", method = RequestMethod.POST)
    public Object editAddress(HttpServletRequest request) {
        EditInfoForm form = new EditInfoForm(request);
        if (!form.verify()) {
            this.setAttr("msg", "验证失败");
            return redirect("/user/myInfo");
        } else {
            User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
            user = DaoFactory.getDao(UserDao.class).editAddress(user, form.getString("address"), form.getString("phone"), form.getString("postNumber"), form.getString("trueName"));
            request.getSession().setAttribute("user", user);
            return redirect("/user/myInfo");
        }
    }


//    /**
//     * 得到用户接口
//     */
//    @RequestMapping(value = "getUser", method = RequestMethod.GET)
//    public Object getUser(@RequestParam(value = "name", required = true) String name, HttpServletRequest request, HttpServletResponse response) {
//        this.clearAttr(request);
//        UserDao userDao = DaoFactory.getDao(UserDao.class);
//        List<User> list = userDao.getByName(name);
//        List<Map> json = new ArrayList<Map>();
//        for (int i = 0; i < list.size(); i++) {
//            Map<String, Object> user_map = new HashMap<String, Object>();
//            user_map.put("id", list.get(i).getId());
//            user_map.put("name", list.get(i).getName());
//            json.add(user_map);
//        }
//        return this.renderJson(response, json);
//    }

//

    /**
     * 判断用户名存在接口
     */
    @RequestMapping(value = "findName", method = RequestMethod.POST)
    @ResponseBody
    public Object findName(@RequestParam(value = "name", required = true) String name, HttpServletRequest request, HttpServletResponse response) {
        this.clearAttr(request);
        UserDao userDao = DaoFactory.getDao(UserDao.class);
        Map<String, Object> json = new HashMap<String, Object>();
        if (!userDao.checkName(name)) {
            json.put("result", 1);
        } else {
            json.put("result", 0);
        }
        return json;
    }


    /**
     * 判断邮箱接口
     */
    @RequestMapping(value = "findEmail", method = RequestMethod.POST)
    @ResponseBody
    public Object findEmail(@RequestParam(value = "email", required = true) String name, HttpServletRequest request, HttpServletResponse response) {
        this.clearAttr(request);
        UserDao userDao = DaoFactory.getDao(UserDao.class);
        Map<String, Object> json = new HashMap<String, Object>();
        if (!userDao.checkEmail(name)) {
            json.put("result", 1);
        } else {
            json.put("result", 0);
        }
        return json;
    }


    public void setCookies(User user, HttpServletResponse response) {
        CookiesUtil.setCookie(response, "user", user.getId() + "-" + user.getPassword(), 3600 * 24 * 10, "/", (String) null);
    }

}
